/**
 * @FileName: Receiver.java
 * @Package: com.rabbitmq
 * @author lig134
 * @created 2017/3/8 18:02
 * <p>
 * Copyright 2015 ziroom
 */
package com.rabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * <p></p>
 * 客户端01
 * <PRE>
 * <BR>	修改记录
 * <BR>-----------------------------------------------
 * <BR>	修改日期			修改人			修改内容
 * </PRE>
 *
 * @author lig134
 * @version 1.0
 * @since 1.0
 */
public class Receiver_1 {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        ConnectionFactory connFac = new ConnectionFactory();

        connFac.setHost("master");
        connFac.setUsername("ligen");
        connFac.setPassword("ligen");

        Connection conn = connFac.newConnection();

        Channel channel = conn.createChannel();

        String exchangeName = "news1";
        channel.exchangeDeclare(exchangeName, "fanout");
        channel.basicQos(1);
        //这里使用没有参数的queueDeclare方法创建Queue并获取QueueName
        String queueName = channel.queueDeclare().getQueue();

        //将queue绑定到Exchange中
        channel.queueBind(queueName, exchangeName, "ligen1");

        //配置好获取消息的方式
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, false, consumer);
        //获取消息
        System.out.println("Waiting message ...");
        while (true) {

            //获取消息，如果没有消息，这一步将会一直阻塞
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();

            //确认消息，已经收到
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(),false);
            String msg = new String(delivery.getBody());

            System.out.println("received message[" + msg + "] from " + queueName);
        }
    }

    public static void main1(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException, TimeoutException {

        ConnectionFactory connFac = new ConnectionFactory();

        connFac.setHost("master");
        connFac.setUsername("ligen");
        connFac.setPassword("ligen");

        Connection conn = connFac.newConnection();

        Channel channel = conn.createChannel();

        String exchangeName = "news";
        channel.exchangeDeclare(exchangeName, "fanout");

        //这里使用没有参数的queueDeclare方法创建Queue并获取QueueName
        String queueName = channel.queueDeclare().getQueue();

        //将queue绑定到Exchange中
        channel.queueBind(queueName, exchangeName, "");

        //配置好获取消息的方式
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, true, consumer);

        //循环获取消息
        while (true) {

            //获取消息，如果没有消息，这一步将会一直阻塞
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();

            String msg = new String(delivery.getBody());

            System.out.println("received message[" + msg + "] from " + queueName);
        }

    }
}